#!/bin/bash

# Copyright (c) 2023, Arm Limited and Contributors. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Tip: set the ENV_ALREADY_SET environment variable to any non-empty string to skip installing packages if they are
# already installed in the active virtual environment.
set -ex

function die {
    echo "$@" >&2
    exit 1
}

HERE=$(realpath "$(dirname "$BASH_SOURCE")")
FVP=$1
PYEDMGR=$2
FIRMWARE=$3

export PYTHONPATH=/opt/FVP_Corstone_SSE-300_Ethos-U55/Iris/Python
export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION="python"
export PROTO="$HERE/../src/iot-socket.proto"
export BRIDGEIP=$($HERE/run_in_ns.sh ARMns ifconfig ARMbr | grep inet6 | grep link | head -1 |  awk '{print $2;}')
export BRIDGEINTERFACE="ARMbr"

[[ -z "$BRIDGEIP" ]] && die "BRIDGEIP not set"

# Check command-line args.
[[ -z "$FVP" || -z "$PYEDMGR" || -z "$FIRMWARE" ]] && die "Usage: $BASH_SOURCE <FVP> <pyedmgr src dir> <server binary>"
[[ ! -x "$FVP" && ! -x `which "$FVP"` ]] && die "No such executable: $FVP"
[[ ! -d "$PYEDMGR" ]] && die "No such directory: $PYEDMGR"
[[ ! -f "$FIRMWARE" ]] && die "No such file: $FIRMWARE"

PYEDMGR=$(realpath "$PYEDMGR")
FIRMWARE=$(realpath "$FIRMWARE")

source $HERE/bootstrap.sh

# Install pyedmgr and requirements.
pushd "$PYEDMGR"
if [[ -z "$ENV_ALREADY_SET" ]]; then
    pip3 install -r requirements.txt
    python3 setup.py install
fi
popd

# Install example requirements.
[[ -z "$ENV_ALREADY_SET" ]] && pip3 install -r $HERE/requirements.txt

function random_byte {
    printf "%02X" $[RANDOM%255]
}

function random_mac {    # Locally administered and Unicast Mac address
    echo "5E:$(random_byte):$(random_byte):$(random_byte):$(random_byte):$(random_byte)"
}

# Create test data and run example.
cd "$HERE"
cat >"$HERE/test.json" <<EOF
{
    "$FVP": {
        "1": {
            "firmware": ["$FIRMWARE"],
            "config": "$HERE/MPS3.conf",
            "args": ["-Q", "10", "-C", "mps3_board.smsc_91c111.mac_address=$(random_mac)", "-C", "mps3_board.hostbridge.interfaceName=tap1"]
        },
        "2": {
            "firmware": ["$FIRMWARE"],
            "config": "$HERE/MPS3.conf",
            "args": ["-Q", "10", "-C", "mps3_board.smsc_91c111.mac_address=$(random_mac)", "-C", "mps3_board.hostbridge.interfaceName=tap2"]
        }
    }
}
EOF

trap "{ rm -f test.json; }" EXIT

$HERE/run_in_ns.sh ARMns pytest example.py
